<template>
	<view class="page">
		<view class="top-box">
			<image class="img-top-light" src="http://assets.shinshen.com/static/top-light.png"></image>
			<image class="img-head" src="https://picture.jmgc.vip/4c96d896-88ea-4300-a186-de765c32a21e.jpeg">
			</image>
			</image>

		</view>

		<view v-if='activity != ""' class="center-box">
			<!-- 老虎机 -->
			<Ss-raffle-tiger v-if='type == 1 && prizeList && prizeList.length > 0' ref="tigerMachine" :prize-list="prizeList"></Ss-raffle-tiger>

			<!-- 大转盘 -->
			<!-- <Ss-raffle-turntable :onStopped="handleResult" :prizeList="prizeList" v-if="type==2"></Ss-raffle-turntable> -->

			<!-- 九宫格 -->
			<ss-raffle-9box v-if='type == 3 && prizeList && prizeList.length > 0' ref="nineBoxMachines" :goods="prizeList" @start="startCallBack"></ss-raffle-9box>
		</view>
		<view v-else style='padding-bottom: 50px;'>
			<u-empty mode="search" text='暂无抽奖活动' iconColor='#fff' textColor='#fff'>
			</u-empty>
		</view>
		<view v-if='activity.description' class='tips'>
			<view style='font-weight: bold;'>活动说明:</view>
			<view style='color:#606266'>
				每人可抽{{activity.perUserTimesLimit}}次，您还有{{userLimit}}次抽奖机会
			</view>
			<u-parse :content="activity.description"></u-parse>
		</view>

		<view style='padding-top:30px;padding:10px;width:100%'>
			<u-button type='success' size='large' shape='circle' text='返回' @click='toHome'></u-button>
		</view>

		<view>
			<u-popup :show="show" @close="show = false" mode='bottom' round='10px'>
				<view style='padding:20px 10px'>
					<view style='font-size: 14px;color:#fcbd71'>
						为了方便中奖后核对，我们需要获取您的联系电话
					</view>
					<view>
						<view style='margin-top:20px'>
							<u-button type="success" size='large' open-type="getPhoneNumber"
								@getphonenumber="getPhoneNumber">手机快捷登录
							</u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<view>
			<u-modal :show="showAward" title="抽奖结果" :showCancelButton='true' cancelText='继续抽奖' confirmText='查看奖品' @confirm='toUrl("/pages/mine/draw-log")' @cancel='showAward = false'>
				<view v-if='award.id > 0'>
					<view v-if='award.image' style='margin:auto'>
						<img :src='award.image' style='width:60px;height:60px;margin:auto' />
					</view>
					<view style='padding:10px 0px;'>
						恭喜您，抽中了{{award.giftName}}
					</view>
				</view>
				<view v-else style='color:#909399;text-align: center;'>
					很遗憾，没有中奖
				</view>
			</u-modal>
		</view>
	</view>
</template>

<script>
	import SsRaffleTiger from '@/components/ss-raffle-tiger/ss-raffle-tiger'
	import SsRaffleTurntable from '@/components/ss-raffle-turntable/ss-raffle-turntable'
	import SsRaffle9Box from '@/components/ss-raffle-9box/ss-raffle-9box'
	export default {
		components: {
			SsRaffleTiger,
			SsRaffleTurntable,
			SsRaffle9Box
		},
		data() {
			return { 
				type: 3,
				prizeList: [],
				show: false,
				phone: '',
				activityId: 0,
				activity: '',
				userLimit: 0,
				isLoading: false,
				award: '',
				showAward: false
			};
		},
		onLoad(options) {
			// 根据情况，如果有传，就用对应id，无传，就搜索有效的id
			if (typeof(options.scene) != 'undefined') {
				this.activityId = options.scene
			}
			let api_token = uni.getStorageSync('api_token')
			if(api_token == ''){
				this.wxLogin()
			}else{
				this.getActiviry()
			}
		},
		onShareAppMessage(res) {
			if (this.activityId > 0) {
				return {
					title: '名苑新天地',
					path: `/pages/draw/index?scene=${this.activityId}`,
					imageUrl: 'https://picture.jmgc.vip/bd3cb5a2-911a-4620-a038-e334c807be3a.png'
				}
			} else {
				return {
					title: '名苑新天地',
					path: `/pages/draw/index`,
					imageUrl: 'https://picture.jmgc.vip/bd3cb5a2-911a-4620-a038-e334c807be3a.png'
				}
			}
		},
		onReady() {
		},
		methods: {
			getActiviry() {
				this.showAward = false
				uni.showLoading()
				// 默认生效中的一个抽奖
				let filter = `entity.getStartTime() < datetime.get('now') && entity.getEndTime() > datetime.get('now') && entity.getEnabled() == true`
				if (this.activityId > 0) {
					filter += ` && entity.getId() == ${this.activityId}`
				}
				this.request.get(`api/lottery-activities`, {
					'@filter': filter,
					limit: 1
				}).then((res) => {
					console.log('acc',res.data)
					if (res.data && res.data.length > 0) {
						this.activity = res.data[0]
						// 根据设置类型决定抽奖方式1为老虎机，2为大转盘，3为九宫格
						if(this.activity.extraData && this.activity.extraData.type){
							this.type = this.activity.extraData.type
						}
						// 查自己的抽奖次数
						this.request.get(`api/lottery-records`,{
							'@filter': `entity.getActivity().getId() == ${this.activity.id}`
						}).then((res) => {
							console.log('record',res)
							this.userLimit = parseInt(this.activity.perUserTimesLimit) - res.data.length
						})
						// 查奖品
						this.request.get(`api/lottery-awards`,{
							'@filter': `entity.getActivity().getId() == ${this.activity.id} && entity.getRemains() > 0`,
							'@order': 'entity.value|ASC'
						}).then((res) => {
							uni.hideLoading()
							let hadNoAwards = false
							if(res.data && res.data.length > 0){
								// 将奖品塞入去抽奖数组
								let prizeList = []
								if(this.type == 3){
									for(let i of res.data){
										prizeList.push({
											"image": i.picture ? i.picture : 'https://picture.jmgc.vip/bd3cb5a2-911a-4620-a038-e334c807be3a.png',
											"score": 0,
											"createTime": "2024-10-01 12:00:00",
											"giftName": i.name,
											"oneUserWinNum": 0,
											"giftNum": 0,
											"prizeDrawId": "D98947C55E3144C2A5B0CF43B666D0EC",
											"weight": 1000,
											"giftType": 3,
											"id": i.id,
											"sort": 1
										})
									}
									// 如果不够9个，就加够9个
									if(prizeList.length < 8){
										hadNoAwards = true
										let count = 8 - prizeList.length
										console.log(count)
										for(let i = 0; i < count; i++){
											prizeList.push({
												"image": "http://assets.shinshen.com/static/prizeImage/1692177062649-7.png",
												"score": 0,
												"createTime": "2023-08-17 20:14:13",
												"giftName": "谢谢参与",
												"oneUserWinNum": 0,
												"giftNum": 0,
												"prizeDrawId": "D98947C55E3144C2A5B0CF43B666D0EC",
												"weight": 1000,
												"giftType": 3,
												"id": 0,
												"sort": 1
											})
										}
									}
									// 如果不够8个，再打乱
									if(hadNoAwards){
										prizeList.sort(() => Math.random() - 0.5);
									}
									this.prizeList = prizeList
								}else if (this.type == 1){
									for(let i of res.data){
										prizeList.push({
											"image":  i.picture ? i.picture : 'https://picture.jmgc.vip/bd3cb5a2-911a-4620-a038-e334c807be3a.png',
											"score": 100,
											"createTime": "2023-08-17 20:49:49",
											"giftName": i.name,
											"oneUserWinNum": 0,
											"giftNum": 50,
											"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
											"rule": "ABA",
											"weight": 300,
											"giftType": 2,
											"id": i.id,
											"sort": 1
										})
									}
									this.prizeList = [{
		"image": "http://assets.shinshen.com/static/prizeImage/1692177434635-8.png",
		"score": 100,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "积分",
		"oneUserWinNum": 0,
		"giftNum": 50,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"rule": "ABA",
		"weight": 300,
		"giftType": 2,
		"id": 237,
		"sort": 1
	}, {
		"image": "http://assets.shinshen.com/static/prizeImage/1692177441696-9.png",
		"score": 0,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "谢谢参与",
		"oneUserWinNum": 0,
		"giftNum": 0,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"weight": 1000,
		"giftType": 3,
		"id": 238,
		"sort": 2
	}, {
		"image": "http://assets.shinshen.com/static/prizeImage/1692177454785-0.png",
		"score": 0,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "旅行洗发水",
		"oneUserWinNum": 0,
		"giftNum": 10,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"rule": "AAA",
		"weight": 200,
		"giftType": 1,
		"id": 239,
		"sort": 3
	}, {
		"image": "http://assets.shinshen.com/static/prizeImage/1692177459829-1.png",
		"score": 0,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "谢谢参与",
		"oneUserWinNum": 0,
		"giftNum": 0,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"weight": 1000,
		"giftType": 3,
		"id": 240,
		"sort": 4
	}, {
		"image": "http://assets.shinshen.com/static/prizeImage/1692177463429-2.png",
		"score": 0,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "谢谢参与",
		"oneUserWinNum": 0,
		"giftNum": 0,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"weight": 1000,
		"giftType": 3,
		"id": 241,
		"sort": 5
	}, {
		"image": "http://assets.shinshen.com/static/prizeImage/1692177473553-3.png",
		"score": 0,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "口罩",
		"oneUserWinNum": 0,
		"giftNum": 1,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"rule": "AAA",
		"weight": 100,
		"giftType": 1,
		"id": 242,
		"sort": 6
	}, {
		"image": "http://assets.shinshen.com/static/prizeImage/1692177478954-4.png",
		"score": 0,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "谢谢参与",
		"oneUserWinNum": 0,
		"giftNum": 0,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"weight": 1000,
		"giftType": 3,
		"id": 243,
		"sort": 7
	}, {
		"image": "http://assets.shinshen.com/static/prizeImage/1692177482190-5.png",
		"score": 10,
		"createTime": "2023-08-17 20:49:49",
		"giftName": "积分",
		"oneUserWinNum": 0,
		"giftNum": 507,
		"prizeDrawId": "DF0B19DA1EA04C5A935E39FAD61FB74D",
		"rule": "AAB",
		"weight": 400,
		"giftType": 2,
		"id": 244,
		"sort": 8
	}]
								}
								
							}else{
								uni.showModal({
									title: '',
									content: '还未设置抽奖奖品！',
									showCancel: false,
									success: () => {
										uni.switchTab({
											url: '/pages/index/index'
										})
									}
								})
							}
						})
					}else{
						uni.hideLoading()
					}
				})
			},
			wxLogin() {
				let _this = this
				uni.login({
					success(result) {
						console.log(111, result)
						let code = result.code
						_this.request.get(`wechat/mini/login`, {
							code
						}).then((res) => {
							console.log('login', res)
							const token = res.data.token
							uni.setStorageSync('api_token', token)
							_this.getActiviry()
						})
					}
				})
			},
			toHome() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			handleResult(info) {
				let _this = this
				let item = info
				for(let i of this.prizeList){
					if(i.id == info.id){
						item = i
					}
				}
				console.log('奖品内容',item)
				_this.userLimit--
				_this.award = item
				setTimeout(() => {
					_this.showAward = true
					_this.isLoading = false
				}, 1000)
			},
			// 点击抽奖按钮触发回调
			startCallBack() {
				if(this.userLimit <= 0){
					uni.showToast({
						title: '抽奖次数已用完！',
						icon: 'none'
					})
					return
				}
				if(this.isLoading == true){
					console.log('抽奖中，不能重复点击')
					uni.showToast({
						title: '正在抽奖',
						icon: 'none'
					})
					return
				}
				console.log('点击抽奖')
				// 判断是否已经注册，没有注册的，需要先注册
				let api_token = uni.getStorageSync('api_token')
				if (api_token == '') {
					// 先注册
					this.show = true
					return
				} else {
					// 判断是否已经有客户信息，无的，依然要获取
					this.request.get(`api/user`, {
						'@expands': '["entity.profile"]'
					}).then((res) => {
						if (res.data.profile.__metadata.phone == null || res.data.profile.__metadata.phone == '') {
							this.show = true
							return
						}else{
							// 这里触发后台抽奖的结果，如果正常，就开始滚动，然后再停，res的id决定中奖内容
							if(this.activity == ''){
								uni.showModal({
									title: '',
									content: '抽奖活动已结束!',
									showCancel: false,
									success: () => {
										uni.switchTab({
											url: '/pages/index/index'
										})
									}
								})
								return
							}
							this.isLoading = true
							this.request.post(`api/lottery-records`,{activity: this.activity.id}).then((record) => {
								console.log('抽奖结果',record.data)
								let _this = this
								let res = {
									"giftName": "奖品名",
									"prizeDrawId": "D96933D7E9614CD9A755438C6F3D6629",
									"id": 0,
								}
								if(record.data.award && record.data.award != null && record.data.award.id){
									res.id = record.data.award.id
								}
								console.log(res.id, this.prizeList.map(i => i.id).join('-'))
								// 计算会停在哪里
								const hitIndex = this.prizeList.findIndex(i => i.id == res.id)
								console.log('停留位置',hitIndex)
								// 先开始旋转
								this.$refs.nineBoxMachines.onStart({
									index: hitIndex,
									success() {
										console.log(res)
										_this.handleResult(res)
									}
								})
							}).catch((err) => {
								
							})
						}
					})
				}
				
				
			},
			toUrl(page){
				uni.navigateTo({
					url: page
				})
			},
			getPhoneNumber(e) {
				let _this = this
				if (typeof(e.detail.iv) == 'undefined') {
					uni.showToast({
						title: '获取失败,请手动输入',
						icon: 'none'
					})
					return
				} else {
					uni.login({
						provider: "weixin",
						success: function(res) {
							let data = {
								code: res.code
							}
							_this.request.get("wechat/mini/login", data).then((res) => {
								uni.setStorageSync('api_token', res.data.token);
								if (res.data.data.session_key) {
									let data = {
										sessionKey: res.data.data.session_key,
										iv: e.detail.iv,
										encryptedData: e.detail.encryptedData,
									}
									_this.request.post(`wechat/decrypt-data`, data).then((res) => {
										_this.phone = res.data.phoneNumber
										console.log('phone', res);
										//更新手机号码
										_this.request.put(`api/user-profile`, {
											phone: res.data.phoneNumber
										}).then((res) => {
											console.log(res)
											_this.show = false
											_this.startCallBack()
										})
									})
								} else {
									uni.showToast({
										title: '获取手机号码失败！',
										icon: 'none'
									})
								}
							})
						},
					});
				}
			}
		}

	}
</script>

<style lang="scss">
	.tips {
		background-color: #f3f3f3;
		margin: 20px auto;
		color: #606266;
		border-radius: 10px;
		padding: 10px;
		width: 90%;
	}

	page {
		width: 100%;
		height: 100%;
		background-color: #FF5D00;
		// background-image: url('http://assets.shinshen.com/static/backgroud.png');
		// background-repeat: no-repeat;
		// background-size: 100% 100%;
	}

	.page {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;

		.top-box {
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			z-index: 1;
			font-size: 0;

			.logo {
				position: absolute;
				display: inline-block;
				left: 10rpx;
				top: 30rpx;
				z-index: 2;
				width: 100rpx;
				height: 100rpx;
			}

			.img-head {
				position: absolute;
				top: 0rpx;
				left: 0;
				right: 0;
				margin: 0 auto;
				width: 100%;
				height: 460rpx;
			}

			.img-tiger-head {
				position: absolute;
				top: 50rpx;
				left: 0;
				right: 0;
				margin: 0 auto;
				width: 706rpx;
				height: 252rpx;
			}

			.img-tiger-cloudr {
				position: absolute;
				top: 227rpx;
				right: 0;
				width: 194rpx;
				height: 154rpx;
			}

			.img-tiger-gold1 {
				position: absolute;
				top: 175rpx;
				left: 0;
				width: 177rpx;
				height: 151rpx;
			}

			.img-top-light {
				display: inline-block;
				width: 100%;
				height: 319rpx;
			}
		}

		.center-box {
			width: 80%;
		}

		.bottom-box {
			position: absolute;
			left: 0;
			bottom: 0;
			right: 0;
			z-index: 1;
			font-size: 0;

			.img-bg-bottom {
				display: inline-block;
				width: 100%;
				height: 114rpx;
			}

			.btm-seat {
				position: absolute;
				left: 0;
				bottom: 80rpx;
				right: 0;
				display: block;
				margin: 0 auto;
				width: 80%;
				height: 200rpx;
				z-index: 2;
			}

			.btm-gift {
				position: absolute;
				left: 0;
				bottom: 180rpx;
				right: 0;
				display: block;
				margin: 0 auto;
				width: 52%;
				height: 150rpx;
				z-index: 3;
			}

			.btm-table {
				position: absolute;
				left: 0;
				bottom: 200rpx;
				right: 0;
				display: block;
				margin: 0 auto;
				width: 100%;
				height: 460rpx;
				z-index: 2;
			}
		}
	}
</style>